﻿using System.Configuration;
using System.Linq;

namespace Wisdom.Core
{
    /// <summary>
    /// 表示使用app.config或者web.config进行配置的配置源。
    /// </summary>
    public class AppOrWebConfigSource : IConfigSource
    {
        #region Private Fields
        private WisdomConfigSection config;
        #endregion

        #region Public Constants
        /// <summary>
        /// 设置配置文件默认结点名称为：jiuzhou
        /// </summary>
        public const string DefaultConfigSection = "jiuzhou";
        #endregion

        #region Ctor
        /// <summary>
        /// 构造函数：实始化一个 <c>AppOrWebConfigSource</c> 类
        /// </summary>
        public AppOrWebConfigSource()
        {
            string configSection = DefaultConfigSection;
            try
            {
                object[] configAttributes = typeof(WisdomConfigSection).GetCustomAttributes(false);
                if (configAttributes.Any(p => p.GetType() == typeof(System.Xml.Serialization.XmlRootAttribute)))
                {
                    var xmlRootAttribute = (System.Xml.Serialization.XmlRootAttribute)
                        configAttributes.SingleOrDefault(p => p.GetType() == typeof(System.Xml.Serialization.XmlRootAttribute));
                    if (xmlRootAttribute != null && (!string.IsNullOrEmpty(xmlRootAttribute.ElementName) &&
                                                     !string.IsNullOrWhiteSpace(xmlRootAttribute.ElementName)))
                    {
                        configSection = xmlRootAttribute.ElementName;
                    }
                }
            }
            catch // If any exception occurs, suppress the exception to uuse the default config section.
            {
            }
            LoadConfig(configSection);
        }
        /// <summary>
        /// 构造函数：实始化一个<c>AppOrWebConfigSource</c> 类.
        /// </summary>
        /// <param name="configSectionName">配置结点的名称.</param>
        public AppOrWebConfigSource(string configSectionName)
        {
            LoadConfig(configSectionName);
        }
        #endregion

        #region Private Methods
        private void LoadConfig(string configSection)
        {
            this.config = (WisdomConfigSection)ConfigurationManager.GetSection(configSection);
        }
        #endregion

        #region IConfigSource Members
        /// <summary>
        /// 获得 <see cref="WisdomConfigSection"/> 类实例.
        /// </summary>
        public WisdomConfigSection Config
        {
            get { return this.config; }
        }

        #endregion
    }
}